package com.NULL.phony.filter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.NULL.phony.Helper;

public class SMS extends BroadcastReceiver {
	private SmsMessage sms;

	@Override
	public void onReceive(Context context, Intent intent) {
		parseMessage(intent);
		
		if(sms==null)
			return;
		
		String phoneNumber = sms.getOriginatingAddress();

		if (!Helper.isInContact(context, phoneNumber)) {
			this.abortBroadcast();

			DB db = new DB(context);
			db.add(phoneNumber, sms.getMessageBody());

			int count = db.getCount();

			db.close();

			Helper.notify(context,
					count + " " + context.getString(R.string.BlockMessage));
		}
	}

	private void parseMessage(Intent intent) {
		sms = null;
		try {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				Object[] pdus = (Object[]) bundle.get("pdus");
				for (Object pdu : pdus) {
					sms = SmsMessage.createFromPdu((byte[]) pdu);
					break;
				}
			}
		} catch (Throwable e) {
			
		}
	}
}
